package com.booza.dao;

import java.util.Collection;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.booza.model.PlayerRankings;

/**
 * Hibernate based DAO implementation class for player rankings table.
 */
@Transactional
public class PlayerRankingsDAOImpl implements PlayerRankingsDAO
{
	@Autowired
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory()
	{
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory)
	{
		this.sessionFactory = sessionFactory;
	}

	/**
	 * Find a row by PK in player rankings table.
	 * 
	 * @param id
	 * @return
	 */
	public PlayerRankings findById(Integer id)
	{
		return (PlayerRankings) sessionFactory.getCurrentSession().createCriteria(PlayerRankings.class).add(
				Restrictions.eq("id", id)).uniqueResult();
	}

	/**
	 * Find all rankings for the given user.
	 * 
	 * @param userId
	 *          - user id
	 * @return matching rankings list
	 */
	@SuppressWarnings("unchecked")
	public Collection<PlayerRankings> findRankingsForUser(Integer userId)
	{
		return (Collection<PlayerRankings>) sessionFactory.getCurrentSession().createCriteria(PlayerRankings.class).add(
				Restrictions.eq("accountId", userId)).list();
	}

	/**
	 * Finds the ranking row for the given user and for the given game type.
	 * 
	 * @param userId
	 * @param gameId
	 */
	@SuppressWarnings("unchecked")
	public Collection<PlayerRankings> findRankingsForUserForGame(Integer userId, Integer gameId)
	{
		return (Collection<PlayerRankings>) sessionFactory.getCurrentSession().createCriteria(PlayerRankings.class).add(
				Restrictions.eq("accountId", userId)).add(Restrictions.eq("gameId", gameId)).list();
	}

	/**
	 * Inserts or updates player rankings.
	 * 
	 * @param row
	 */
	public void saveRankings(Collection<PlayerRankings> rankings)
	{
		for (PlayerRankings rank : rankings) {
			saveRankings(rank);
		}
	}

	/**
	 * Updates multiple ranking entries.
	 * 
	 * @param rankings
	 */
	public void saveRankings(PlayerRankings row)
	{
		sessionFactory.getCurrentSession().save(row);
	}
}
